goog.provide('otq.initUpgrade');

goog.require('goog.async.Delay');
goog.require('goog.dom');
goog.require('goog.dom.query');
goog.require('goog.net.XhrIo');

/**
 * @param {Element} field Text field containing the name.
 * @param {Element} label Label for reporting availability to user.
 * @constructor
 */
otq.nameChecker = function(field, label) {
	/** @type {goog.async.Delay} */
	this.delay_ = null;

	this.field_ = field;
	this.label_ = label;
}

otq.nameChecker.prototype.init = function() {
	this.delay_ = new goog.async.Delay(goog.bind(this.check_, this), 100);
  goog.events.listen(
			this.field_,
			goog.events.EventType.KEYUP,
			goog.bind(this.onchange_, this));
};

otq.nameChecker.prototype.onchange_ = function() {
	this.label_.innerHTML = '';
	this.label_.style.color = 'black';

	// Reset the delay counter.
	this.delay_.start();
};

otq.nameChecker.prototype.response_ = function(e) {
	var xhr = e.target;
	var obj = xhr.getResponseJson();
	window.console.log('returned:');
	window.console.log(obj);
	if (!obj) {
		this.label_.innerHTML = 'Unexpected error';
		this.label_.style.color = 'red';
	} else if (obj.error) {
		this.label_.innerHTML = 'Unexpected error: ' + obj.error;
		this.label_.style.color = 'red';
	} else if (!obj["valid"]) {
		this.label_.innerHTML = 'Name is invalid, must match [a-z][a-z0-9\\-_]';
		this.label_.style.color = 'darkred';
	} else if (!obj["available"]) {
		this.label_.innerHTML = 'Name is unavailable';
		this.label_.style.color = 'darkred';
	} else {
		this.label_.innerHTML = 'Name is available';
		this.label_.style.color = 'darkgreen';
	}
};

otq.nameChecker.prototype.check_ = function() {
	var name = this.field_.value;
	window.console.log('check_: '+name);
	goog.net.XhrIo.send('/checkname/' + name, goog.bind(this.response_, this));
};

otq.initUpgrade = function() {
	window.console.log('initUpgrade called');
	var checker = new otq.nameChecker(
			document.getElementsByName('shortname')[0],
			document.getElementById('shortnameAvail'));
	checker.init();
};

goog.exportSymbol('otq.initUpgrade', otq.initUpgrade);
